// void, Obj This

Hero this;
int i, j, k;
Obj u;

this = This.AsHero;

if(IsAIPlayer(.player)){
	for (i = 0; i<.army.count; i+=1)
		if (.army[i].command == "form_move")
			.army[i].SetCommand("idle");
} else {
	if(.HasArmy) 
		.SetCommand("stand_position");
}
//pr("hero idle1");
while(!.Stop(1000));

while(1){

	if(.IsVisible){
		u = .BestTargetInSquadSightMisZeroDamage;
		if(u.IsAlive)
		if(.IsValidTarget(u)){
			if(!u.IsHeirOf("BaseAnimal"))
			if(.DistTo(u) > .min_range){
				
				if(.HasArmy){
					if(u.AsUnit.command != "retreat_notai" &&
						u.AsUnit.command != "retreat_bld_notai"){
						if(Intersect(ObjsInRange(this, "BaseTownhall", 800), EnemyObjs(.player, "BaseTownhall")).count == 0){
							Sleep(rand(50)+50);
							.AddCommand(true, "advance", u.posRH);
							return;
						}
					}
				} else {
					while(1){
						while(!.GotoAttack(u, 1500, false, 15000)){
							if(!.IsVisible) break;
							u = .BestTargetInSquadSightMisZeroDamage;
							if(!.IsValidTarget(u)) break;
							if(.DistTo(u) < .min_range) break;
						}
						
						if(!.IsVisible) break;
						u = .BestTargetInSquadSightMisZeroDamage;
						if(!.IsValidTarget(u)) break;
						if(.DistTo(u) < .min_range) break;
						if(u.IsHeirOf("BaseAnimal")) break;
						
						while(.Attack(u)){
							if(!.IsValidTarget(u)) break;
							if(.DistTo(u) < .min_range) break;
							if(!.IsVisible) break;
						}
						if(!.IsVisible) break;
						u = .BestTargetInSquadSightMisZeroDamage;
						if(!.IsValidTarget(u)) break;
						if(.DistTo(u) < .min_range) break;
					}
				}
				.FormSetupAndMoveTo(.pos, 0, 0, true);
				.FormKeepMoving(1500);
				continue;
			}
		}
	}

	if (.AI)
	if (!.GetHolderSett.IsValid)
	if (IsWaterLsa(GetGAIKA(this).LSA))	{
		/// leave the coast
		point pt;
		pt.Set(.pos.x + (150 - rand(300)), .pos.y + (150 - rand(300)));
		if (pt.InRect(GetMapRect))
		if (IsPassable3x3(pt))
		if (!IsWaterLsa(pt.GetGAIKA.LSA)) {
			Sleep(rand(80) + 20);
			.AddCommand(true, "move", pt);
			return;
		}
	}

	if(.Stop(2000))
		.Idle(1900 + rand(100));
	while(.InHolder){
		//pr("Idle: InHolder");
		.Idle(5000 + rand(1000));
	}
}
